package com.cass.controller;

import com.cass.entity.Token;
import com.cass.entity.User;
import com.cass.service.UserService;
import com.cass.uilts.JwtUtil;
import com.cass.uilts.Result;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.mybatis.logging.Logger;
import org.mybatis.logging.LoggerFactory;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/login")
@RequiredArgsConstructor
@Slf4j
public class LoginController {
    private final UserService userService;
    private static final Logger logger = LoggerFactory.getLogger(StudentController.class);
   @PostMapping()
    public Result<?> login(@RequestBody User user) {
        // 验证用户名和密码
        User dbUser = userService.getUserByUsernameAndPassword(user.getUsername(), user.getPassword());
        if (dbUser == null) {
           return Result.error("用户名或密码错误");
        }

        // 创建要放入 JWT 的 claims
        Map<String, Object> claims = new HashMap<>();
        claims.put("userId", dbUser.getId());
        claims.put("username", dbUser.getUsername());

        // 生成 JWT token
        String data = JwtUtil.generate(claims);
        Token  token = new Token(user.getUsername(),data);
        // 返回 token
        return Result.success(token);
    }
}
